package streamproc;

import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.util.Vector;

import streamdef.StreamDefinitionManager;
import event.Event;
import event.EventFormatManager;

public class CleanerComponent extends ChainComponent {
	private static CleanerComponent sInstance = null;

	public static CleanerComponent instance() {
		if (sInstance == null)
			sInstance = new CleanerComponent();

		return sInstance;
	}

	// IDs that can be processed -> IDs that are used in other queries !
	private Vector<Long> streamIDs = null;

	private CleanerComponent() {
		streamIDs = new Vector<Long>();
	}

	public void reset() {
		if (streamIDs != null)
			streamIDs.clear();
	}

	protected void finalize() {
		reset();
	}

	public void init() {
		reset();

		Vector<Long> allIDs = EventFormatManager.instance().getValidStreamIDs();
		for (int i = 0; i < allIDs.size(); ++i) {
			if (StreamDefinitionManager.instance()
					.streamIDIsUsedInOtherQueries(allIDs.get(i)))
				streamIDs.add(new Long(allIDs.get(i)));
		}
	}

	public synchronized void processByteArray(long streamID, byte[] data) {
		if (!streamIDs.contains(streamID))
			return;

		try {
			Event e = new Event(streamID, true, true, false, data);
			next.processEvent(e);
		} catch (BufferOverflowException e) {
			e.printStackTrace();
		} catch (BufferUnderflowException e) {
			e.printStackTrace();
		}
	}

	public synchronized void processByteArrayWithTimestamp(long streamID,
			byte[] data, java.sql.Timestamp timestamp) {
		if (!streamIDs.contains(streamID))
			return;
		try {
			Event e = new Event(streamID, true, true, false, data, timestamp);
			next.processEvent(e);
		} catch (BufferOverflowException e) {
			e.printStackTrace();
		} catch (BufferUnderflowException e) {
			e.printStackTrace();
		}
	}

	public synchronized void processEvent(Event e) {
		// Events will only be created if they have a valid streamID
		// -> no check needed

		next.processEvent(e);
	}
}
